package com.woniu.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.customer.entity.CustomerOrder;
import com.woniu.customer.mapper.CustomerOrderMapper;
import com.woniu.finance.entity.Tender;
import com.woniu.finance.mapper.TenderMapper;
import com.woniu.platform.entity.vo.PlatformRepay;
import com.woniu.platform.mapper.PlatformRepayMapper;
import com.woniu.platform.service.PlatformRepyService;
import com.woniu.util.utils.HttpResult;
import com.woniu.util.utils.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PlatformRepyServiceImpl implements PlatformRepyService {
    @Autowired
    private PlatformRepayMapper platformRepayMapper;
    @Autowired
    private TenderMapper tenderMapper;
    @Autowired
    private CustomerOrderMapper customerOrderMapper;

    /**
     * 分页查询带还款信息
     * @param param
     * @return
     */
    @Override
    public HttpResult queryRepyList(RequestParam<PlatformRepay> param) {
        PageHelper.startPage(param.getPageNum(),param.getPageSize());
        List<PlatformRepay> repayList = platformRepayMapper.queryRepay(param.getData().getFinanceName(),param.getData().getCoreName());
        PageInfo pageInfo = new PageInfo(repayList);
        return new HttpResult().ok(pageInfo);
    }

    /**
     * 把钱给用户后的操作
     * @param repay
     * @return
     */
    @Override
    @Transactional
    public HttpResult afterRepy(List<PlatformRepay> repay) {
        List<Integer> ids = repay.stream().map(e ->e.getTenderId()).collect(Collectors.toList());
        //修改标的状态
        tenderMapper.afterRepay(ids);
        Tender tender = new Tender();
        for (Integer id: ids) {
            QueryWrapper<CustomerOrder> queryWrap = new QueryWrapper<CustomerOrder>();
            queryWrap.eq("tender_id",id);
            tender = tenderMapper.selectById(id);
            CustomerOrder customerOrder = customerOrderMapper.selectOne(queryWrap);
            customerOrder.setInvestmentAmount(customerOrder.getLoseMoney()
                    .multiply(BigDecimal.valueOf(tender.getAnnualizedInterestRate())) );
            customerOrderMapper.updateById(customerOrder);
        }
        return new HttpResult().ok();
    }
}
